﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrossQuery.ConditionQuery
{
    public class BooleanCondition : MultiSelectCondition
    {

        public BooleanCondition(string database, string table, string field)
        {
            this.database_name = database;
            this.table_name = table;
            this.field_name = field;
            ExtractValues();
        }

        public new string Type 
        { 
            get { return "Bool"; }
        }

        public override string ToSQLString()
        {
            // if no value selected, just ignore this condition
            if (selected_values == null || selected_values.Count == 0)
                return "true";
            string result = "";
            string left = String.Format(" `{0}`.`{1}`", table_name, field_name);
            bool true_enable = false, false_enable = false;
            foreach (int index in selected_values) {
                if (index == 0)
                    true_enable = true;
                else if (index < candidate_values.Count)
                    false_enable = true;
            }
            if (true_enable && false_enable)
                result = left + "=1 OR " + left + " <> 1 ";
            else if (true_enable)
                result = left + "=1 ";
            else if (false_enable)
                result = left + "<>1 OR " + left + " IS NULL ";
            else // invalid input
                result = "true";
            return result;
        }

        private void ExtractValues()
        {
            this.candidate_values = new List<ConditionValue>();
            candidate_values.Add(new ConditionValue("1", "是"));
            candidate_values.Add(new ConditionValue("0", "否"));
        }
    }
}
